package soar.template.springboot.mq.alimq.producer.app;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;

import soar.template.springboot.mq.alimq.producer.appconfig.AppConfig;

@Component
public class MessageProducer implements CommandLineRunner
{
    private final static Logger logger = LoggerFactory
            .getLogger(MessageProducer.class);

    @Resource
    private AppConfig appconfig;

    @Resource(name = "sendMainProducer")
    private ProducerBean sendMainProducer;

    @Override
    public void run(String... args) throws Exception
    {
        try
        {
            for (int i = 0; i < 100; i++)
            {
                String body = "测试" + i;
                Message msg = new Message(appconfig.alimq.sendMain.topic,
                        appconfig.alimq.sendMain.tags, body.getBytes());
                SendResult res = sendMainProducer.send(msg);
                if (res != null)
                {
                    logger.info("id({}) send({}) successfully",
                            res.getMessageId(), body);
                }
                else
                {
                    logger.error("send result null");
                }
            }
        }
        catch (Exception e)
        {
            if (e.getMessage() != null)
                logger.error("fail: {}", e);
        }
        finally
        {
        }

        System.exit(0);
    }
}
